package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dto.WmUserDto;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author TheCai
 * @date 2021/5/25 19:14
 **/
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    //登录
    @Override
    public ResponseResult login(WmUserDto dto) {
        //1.检查参数
        if (StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(
                    AppHttpCodeEnum.PARAM_REQUIRE,"用户名或密码不能为空");
        }

        //2 查询自媒体用户
        WmUser wmUser = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));

        if (null==wmUser){
            return ResponseResult.errorResult(
                    AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        //3 比对密码
        String inputPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + wmUser.getSalt()).getBytes());
        if (!wmUser.getPassword().equals(inputPwd)){
            return ResponseResult.errorResult(
                    AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //4 返回jwt结果
        //用userId得到token
        String token = AppJwtUtil.getToken(wmUser.getId());
        //准备一个map来接收值
        Map result = new HashMap<>();
        //塞入token
        result.put("token",token);
        //把关键信息隐藏一下
        wmUser.setSalt("");
        wmUser.setPassword("");
        //塞入user
        result.put("user",wmUser);
        return ResponseResult.okResult(result);
    }
}
